package com.mantru.iotpot.setting;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;


import com.mantru.iotpot.ApplicationClass;
import com.mantru.iotpot.Begin.BeginSetActivity;
import com.mantru.iotpot.R;
import com.mantru.iotpot.Util.ToastUtils;
import com.mantru.iotpot.eventbus.EventMessage;
import com.mantru.iotpot.modbus.Common;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import java.io.IOException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class UpgradeIapActivity extends AppCompatActivity implements View.OnClickListener {
    private ApplicationClass ac;
    private TextView time;
    private TextView size;
    private Button download;
    private Button cancel;
    private TextView text1;
    private LinearLayout box;
    private ProgressBar progressBar1;
    private TextView progressBar_text1;
    private ProgressBar progressBar2;
    private TextView progressBar_text2;
    private LinearLayout back;
    private String newVersion; //新版本号
    private String fileUrl; //bin文件的下载地址
    private int isNeedUpgrade;//是否需要升级，1是、0否
    private int down = 0;//0表示下载，1表示安装
    private DownloadTask mDownloadTask;
    private TextView text2;
    private int countdownSeconds = 5;// 倒计时变量
    private File downloadFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upgrade_iap);
        EventBus.getDefault().register(this); // 注册 EventBus
        ac = ((ApplicationClass)getApplication());
        initialization();//初始化控件
        getJson();//获取JSON数据
    }
    //初始化控件
    private void initialization(){
        back = findViewById(R.id.upgrade_iap_back);
        time = findViewById(R.id.upgrade_iap_time);
        size = findViewById(R.id.upgrade_iap_size);
        download = findViewById(R.id.upgrade_iap_download);
        cancel = findViewById(R.id.upgrade_iap_cancel);
        text1 = findViewById(R.id.upgrade_iap_text1);
        text2 = findViewById(R.id.upgrade_iap_text2);//提示
        box = findViewById(R.id.upgrade_iap_box);
        progressBar1 = findViewById(R.id.upgrade_iap_progressbar1);
        progressBar_text1 = findViewById(R.id.upgrade_iap_progressbar_text1);
        progressBar2 = findViewById(R.id.upgrade_iap_progressbar2);
        progressBar_text2 = findViewById(R.id.upgrade_iap_progressbar_text2);
        back.setOnClickListener(this);
        download.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.upgrade_iap_back){//点击返回
            if (down == 0){
                finish();
            }else {
                //Toast.makeText(this, "安装的过程中不可取消任务，请耐心等待", Toast.LENGTH_SHORT).show();
                ToastUtils.show(this, "安装的过程中不可取消任务，请耐心等待");
            }
        } else if (v.getId() == R.id.upgrade_iap_download) {//点击下载
            if (isNeedUpgrade == 1){//需要升级
                download.setVisibility(View.GONE);
                text1.setVisibility(View.GONE);
                cancel.setVisibility(View.VISIBLE);
                box.setVisibility(View.VISIBLE);
                UpgradeIAP();
            }else {
                //Toast.makeText(this, "当前已经是最新的版本", Toast.LENGTH_SHORT).show();
                ToastUtils.show(this, "当前已经是最新的版本");
            }
        } else if (v.getId() == R.id.upgrade_iap_cancel) {//点击取消下载
            if (down == 0){//下载的过程中取消
                //终止下载任务
                stopUpgradeIAP();
                download.setVisibility(View.VISIBLE);
                text1.setVisibility(View.VISIBLE);
                cancel.setVisibility(View.GONE);
                box.setVisibility(View.GONE);
            } else if (down == 1) {//安装的过程中
                //Toast.makeText(this, "安装的过程中不可取消任务，请耐心等待", Toast.LENGTH_SHORT).show();
                ToastUtils.show(this, "安装的过程中不可取消任务，请耐心等待");
            }
        }
    }
    private void getJson() {
        // 创建 OkHttpClient 实例
        OkHttpClient client = new OkHttpClient();
        // 构建请求 URL
        String url = Common.API_Server_Url + "?txt_type=/potnew/init_data/&save_type=check_iap_upgrade&device_id=" + ac.activity_device_id;
        // 创建请求
        Request request = new Request.Builder()
                .url(url)
                .build();
        // 异步执行请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 请求失败处理
                Log.e("UpgradeIapActivity", "请求失败: " + e.getMessage());
                runOnUiThread(() -> {
                    //Toast.makeText(UpgradeIapActivity.this, "请求升级信息失败", Toast.LENGTH_SHORT).show();
                    ToastUtils.show(UpgradeIapActivity.this, "请求升级信息失败");
                });
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    // 获取响应体
                    String jsonStr = response.body().string();
                    try {
                        // 将 JSON 字符串转换为 JSONObject
                        JSONObject jsonObject = new JSONObject(jsonStr);
                        // 获取 "success" 字段
                        boolean success = jsonObject.optBoolean("success");
                        if (success) {
                            // 获取 "upgrade_data" 对象
                            JSONObject upgradeData = jsonObject.optJSONObject("upgrade_data");
                            // 获取是否需要升级
                            isNeedUpgrade = upgradeData.optInt("is_need_upgrade");
                            // 获取新版本号
                            newVersion = upgradeData.optString("new_version");
                            // 获取下载地址
                            fileUrl = upgradeData.optString("file_url");
                            Log.d("UpgradeIapActivity","isNeedUpgrade: " + isNeedUpgrade + " newVersion: " + newVersion + " fileUrl: " + fileUrl);
                            // 如果需要升级且 fileUrl 不为空，则获取文件元信息
                            if (isNeedUpgrade == 1 && fileUrl != null && !fileUrl.isEmpty()) {
                                getFileMetadata(fileUrl);
                            }
                        } else {
                            // 服务器返回失败
                            runOnUiThread(() -> {
                                //Toast.makeText(UpgradeIapActivity.this, "获取升级信息失败", Toast.LENGTH_SHORT).show();
                                ToastUtils.show(UpgradeIapActivity.this, "请求升级信息失败");
                            });
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        // JSON 解析错误处理
                        runOnUiThread(() -> {
                            //Toast.makeText(UpgradeIapActivity.this, "解析升级信息出错", Toast.LENGTH_SHORT).show();
                            ToastUtils.show(UpgradeIapActivity.this, "解析升级信息出错");
                        });
                    }
                } else {
                    // HTTP 请求不成功
                    Log.e("UpgradeIapActivity", "HTTP 请求不成功: " + response.code());
                    runOnUiThread(() -> {
                        //Toast.makeText(UpgradeIapActivity.this, "获取升级信息失败，HTTP 错误码: " + response.code(), Toast.LENGTH_SHORT).show();
                        ToastUtils.show(UpgradeIapActivity.this, "获取升级信息失败，HTTP 错误码: " + response.code());
                    });
                }
            }
        });
    }
    // 获取文件元信息
    private void getFileMetadata(String fileUrl) {
        if (fileUrl == null || fileUrl.isEmpty()) {
            Log.e("UpgradeIapActivity", "文件 URL 为空，无法获取文件元信息");
            runOnUiThread(() -> {
                //Toast.makeText(UpgradeIapActivity.this, "文件 URL 为空，无法获取文件信息", Toast.LENGTH_SHORT).show();
                ToastUtils.show(UpgradeIapActivity.this, "文件 URL 为空，无法获取文件信息");
            });
            return;
        }
        OkHttpClient client = new OkHttpClient();
        // 构建请求
        Request request = new Request.Builder()
                .url(fileUrl)
                .head() // 使用 HEAD 请求
                .build();
        // 异步执行请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 请求失败处理
                Log.e("UpgradeIapActivity", "获取文件元信息失败: " + e.getMessage());
                runOnUiThread(() -> {
                    //Toast.makeText(UpgradeIapActivity.this, "获取文件信息失败", Toast.LENGTH_SHORT).show();
                    ToastUtils.show(UpgradeIapActivity.this, "获取文件信息失败");
                });
            }
            @Override
            public void onResponse(Call call, Response response) {
                if (response.isSuccessful()) {
                    // 从响应头获取文件大小（字节）
                    final long contentLength; // 声明为 final
                    if (response.header("Content-Length") != null) {
                        contentLength = Long.parseLong(response.header("Content-Length"));
                    } else {
                        contentLength = -1;
                    }
                    // 获取最后修改时间
                    final String lastModified = response.header("Last-Modified");
                    // 格式化最后修改时间
                    final String formattedDate; // 声明为 final
                    if (lastModified != null) {
                        formattedDate = toFriendlyDateTime(lastModified);
                    } else {
                        formattedDate = null;
                    }
                    // 在主线程中更新 UI
                    runOnUiThread(() -> {
                        // 直接使用字节为单位显示文件大小
                        String fileSize = String.valueOf(contentLength) + " 字节";
                        String publishTime = formattedDate != null ? formattedDate : "未知发布时间";
                        // 更新 UI 组件，例如在下载按钮下方显示文件信息
                        size.setText(fileSize);
                        time.setText(publishTime);
                    });
                } else {
                    // HTTP 请求不成功
                    Log.e("UpgradeIapActivity", "获取文件元信息失败，HTTP 错误码: " + response.code());
                    runOnUiThread(() -> {
                        //Toast.makeText(UpgradeIapActivity.this, "获取文件信息失败，HTTP 错误码: " + response.code(), Toast.LENGTH_SHORT).show();
                        ToastUtils.show(UpgradeIapActivity.this, "获取文件信息失败，HTTP 错误码: " + response.code());
                    });
                }
            }
        });
    }
    // 将日期格式转换为 "yyyy-MM-dd HH:mm" 格式
    private String toFriendlyDateTime(String lastModified) {
        SimpleDateFormat inputFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
        try {
            Date date = inputFormat.parse(lastModified);
            return outputFormat.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return lastModified; // 如果解析失败，返回原始字符串
        }
    }

    // 下载 IAP 的方法
    private DownloadTask.DownloadListener mDownloadListener = new DownloadTask.DownloadListener() {
        @Override
        public void onProgressUpdate(final int progress) {
            runOnUiThread(() -> {
                progressBar1.setProgress(progress);
                progressBar_text1.setText(progress + "%");
            });
        }

        @Override
        public void onDownloadComplete() {
            runOnUiThread(() -> {
                //Toast.makeText(UpgradeIapActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
                ToastUtils.show(UpgradeIapActivity.this, "下载完成");
                progressBar1.setProgress(100);
                progressBar_text1.setText("100%");
                String localFilePath = downloadFile.getAbsolutePath();
                Log.d("UpgradeIapActivity","localFilePath: " + localFilePath);
                // 这里可以添加下载完成后的逻辑，如验证文件完整性、开始升级等
                down = 1;
                installIAP(localFilePath); // 下载完成之后调用安装的方法
            });
        }

        @Override
        public void onDownloadFailed(final String message) {
            runOnUiThread(() -> {
                //Toast.makeText(UpgradeIapActivity.this, message, Toast.LENGTH_SHORT).show();
                ToastUtils.show(UpgradeIapActivity.this, message);
            });
        }
    };

    // 下载 IAP 的方法
    private void UpgradeIAP() {
        if (fileUrl == null || fileUrl.isEmpty()) {
            Log.e("UpgradeIapActivity", "文件 URL 为空，无法进行升级");
            runOnUiThread(() -> {
                //Toast.makeText(UpgradeIapActivity.this, "文件 URL 为空，无法进行升级", Toast.LENGTH_SHORT).show();
                ToastUtils.show(UpgradeIapActivity.this, "文件 URL 为空，无法进行升级");
            });
            return;
        }
        // 创建下载目录和文件
        File downloadDir = new File(getExternalFilesDir(null), "downloads");
        if (!downloadDir.exists()) {
            downloadDir.mkdirs();
        }
        downloadFile = new File(downloadDir, "iap_upgrade.bin");
        if (downloadFile.exists()) {
            downloadFile.delete();
        }
        mDownloadTask = new DownloadTask(fileUrl, downloadFile, mDownloadListener);
        mDownloadTask.start();
    }

    //安装IAP的方法
    private void installIAP(String file_path){
        Boolean result = ac.IAP_InstallStart(file_path);
        Log.d("UpgradeIapActivity","result: " + result);
        if (!result){
            //Toast.makeText(this, "安装失败", Toast.LENGTH_SHORT).show();
            ToastUtils.show(UpgradeIapActivity.this, "安装失败");
        }else {

        }
    }

    // 终止下载任务的方法
    private void stopUpgradeIAP() {
        if (mDownloadTask != null) {
            mDownloadTask.cancel();
            Log.d("UpgradeIapActivity", "下载任务已取消");
        }
        // 额外的清理操作，例如删除部分下载文件
        File downloadDir = new File(getExternalFilesDir(null), "downloads");
        if (downloadDir.exists()) {
            File downloadFile = new File(downloadDir, "iap_upgrade.bin");
            if (downloadFile.exists()) {
                downloadFile.delete();
                Log.d("UpgradeIapActivity", "已删除部分下载文件");
            }
        }
        // 更新 UI 表示下载已取消
        runOnUiThread(() -> {
            download.setVisibility(View.VISIBLE);
            text1.setVisibility(View.VISIBLE);
            cancel.setVisibility(View.GONE);
            box.setVisibility(View.GONE);
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this); // 注销 EventBus
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMessage(EventMessage eventMessage) {
        if (eventMessage.id == EventMessage.MSG_ID_IAP_InstallProgress) {//接受安装进度
            try {
                JSONObject messageJson = new JSONObject(eventMessage.message);
                Log.d("UpgradeIapActivity","开始获取安装进度messageJson: " + messageJson);
                int currentValue = messageJson.optInt("cur_value");
                int maxValue = messageJson.optInt("max_value");
                int progress = (maxValue != 0) ? (currentValue * 100 / maxValue) : 0;
                updateInstallProgress(progress);
            } catch (JSONException e) {
                Log.d("UpgradeIapActivity","获取安装进度失败");
                e.printStackTrace();
            }
        } else if (eventMessage.id == EventMessage.MSG_ID_IAP_InstallFinish) {//接收到安装完成的消息之后
            Log.d("UpgradeIapActivity","安装完成");
            startCountdown();
        } else if (eventMessage.id == EventMessage.MSG_ID_IAP_InstallError) {//接收到安装失败的时候
            Log.d("UpgradeIapActivity","安装失败");
            text2.setText("提示：安装失败");
            down = 0;
        }
    }

    //更新安装进度条
    private void updateInstallProgress(int progress) {
        progressBar2.setProgress(progress);
        progressBar_text2.setText(progress + "%");
    }

    // 开始倒计时
    private void startCountdown() {
        countdownSeconds = 5; // 重置倒计时秒数
        text2.setText("提示：安装完成，" + countdownSeconds + "秒之后重启设备");
        new Thread(() -> {
            for (int i = countdownSeconds - 1; i >= 0; i--) {
                try {
                    Thread.sleep(1000); // 每秒更新一次倒计时
                    int finalI = i;
                    runOnUiThread(() -> {
                        countdownSeconds = finalI;
                        text2.setText("提示：安装完成，" + finalI + "秒之后重启设备");
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 倒计时结束，跳转到指定界面
            runOnUiThread(() -> {
                 Intent intent = new Intent(UpgradeIapActivity.this, BeginSetActivity.class);
                 startActivity(intent);
                 finish(); // 如果需要关闭当前活动
            });
        }).start();
    }
}